package com.zqwh.storemonitor.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.zqwh.storemonitor.R;
import com.zqwh.storemonitor.domain.Monitor;
import com.zqwh.storemonitor.domain.MonitorBell;
import com.zqwh.storemonitor.domain.Shop;
import com.zqwh.storemonitor.domain.ShopBell;
import com.zqwh.storemonitor.ezviz.EZUtils;
import com.zqwh.storemonitor.model.WatcherModel;
import com.zqwh.yj.sdk.utils.LogUtils;
import com.zqwh.yj.sdk.utils.SharePreferencesUtils;
import com.zqwh.yj.sdk.utils.ToastUtils;
import com.zqwh.yj.sdk.utils.httpRequest.subscribers.NetCallback;
import com.zqwh.yj.sdk.widget.monindicator.MonIndicator;

import java.util.ArrayList;
import java.util.List;

import static com.zqwh.storemonitor.BundleKey.KEY_STORE_SPAN_COUNT;
import static com.zqwh.storemonitor.Config.STORE_SPAN_COUNT;
import static com.zqwh.storemonitor.StoreMonitorApplication.getOpenSDK;
import static com.zqwh.storemonitor.StoreMonitorApplication.sSelectedShop;
import static com.zqwh.storemonitor.StoreMonitorApplication.sShopWatcher;

public class StoreListActivity extends BaseActivity {
    public static final int MSG_START_PLAY = 0;
    public static final int MSG_TRY_AGAIN = 1;

    private WatcherModel watcherModel;

    private RecyclerView rvShopList;
    private RelativeLayout rlMask;
    private RelativeLayout rlTalk;
    private ImageView imgCloseDialog;
    private TextView tvTalkTip;
    private MonIndicator miTalking;

    private StoreAdapter adapter;
    private List<Shop> shopList;
    private boolean isDataLoaded;
    private Shop currentTalkShop;
    private int currentTalkPosition;
    private StoreAdapter.LocalViewHolder currentTalkHolder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_list);
        watcherModel = new WatcherModel(this);
        shopList = new ArrayList<>();
        isDataLoaded = false;
        setView();
        initToolbar();
        getDeviceList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startRealPlay();
    }

    private void initToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.inflateMenu(R.menu.store_menu);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.action_arrange_1){
                    SharePreferencesUtils.writeIntSharedPreferences(StoreListActivity.this, KEY_STORE_SPAN_COUNT, 1);
                    recreate();
                } else if (item.getItemId() == R.id.action_arrange_2){
                    SharePreferencesUtils.writeIntSharedPreferences(StoreListActivity.this, KEY_STORE_SPAN_COUNT, 2);
                    recreate();
                } else if (item.getItemId() == R.id.action_arrange_4){
                    SharePreferencesUtils.writeIntSharedPreferences(StoreListActivity.this, KEY_STORE_SPAN_COUNT, 4);
                    recreate();
                } else if (item.getItemId() == R.id.action_exit){
                    startActivity(new Intent(StoreListActivity.this, LoginActivity.class));
                    SharePreferencesUtils.writeStringSharedPreferences(StoreListActivity.this, "ACCOUNT", "");
                    SharePreferencesUtils.writeStringSharedPreferences(StoreListActivity.this, "PWD", "");
                    finish();
                }
                return true;
            }
        });
    }

    private void startRealPlay() {
        if (isDataLoaded) {
            handler.sendEmptyMessageDelayed(MSG_START_PLAY, 1000);
        }else {
            handler.sendEmptyMessageDelayed(MSG_TRY_AGAIN, 1000);
        }
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == MSG_START_PLAY) {
                for (Shop shop : shopList) {
                    shop.getRepresentMonitorPlayer().setSurfaceHold(shop.getRepresentMonitorSv().getHolder());
                    shop.getRepresentMonitorPlayer().setPlayVerifyCode(shop.getRepresentMonitorVerifyCode());
                    shop.getRepresentMonitorPlayer().setHandler(new Handler(new Handler.Callback() {
                        @Override
                        public boolean handleMessage(@NonNull Message msg) {
                            switch (msg.what) {
                                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_SUCCESS:
                                    startTalkSuccess();
                                    break;
                                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_STOP:
                                    LogUtils.logout("MSG_REALPLAY_VOICETALK_STOP");
                                    break;
                                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_FAIL:
                                    ErrorInfo errorInfo = (ErrorInfo) msg.obj;
                                    startTalkFail();
                                    break;
                                case EZConstants.MSG_GOT_STREAM_TYPE:
                                    LogUtils.logout("handleMessage -->" + "获取到当前取流类型");
                                    break;
                                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                                    //播放成功
                                    LogUtils.logout("handleMessage -->" + "播放成功");
                                    break;
                                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_STOP_SUCCESS:
                                    //播放成功
                                    LogUtils.logout("handleMessage -->" + "停止成功");
                                    break;
                                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_FAIL:
                                    //播放失败,得到失败信息
                                    ErrorInfo errorinfo = (ErrorInfo) msg.obj;
                                    //得到播放失败错误码
                                    int code = errorinfo.errorCode;
                                    //得到播放失败模块错误码
                                    String codeStr = errorinfo.moduleCode;
                                    //得到播放失败描述
                                    String description = errorinfo.description;
                                    //得到播放失败解决方方案
                                    String sulution = errorinfo.sulution;
                                    LogUtils.logout("handleMessage -->播放失败,得到失败信息: " + errorinfo.toString());
                                    break;
                                case EZConstants.MSG_VIDEO_SIZE_CHANGED:
                                    //解析出视频画面分辨率回调
                                    try {
                                        String temp = (String) msg.obj;
                                        String[] strings = temp.split(":");
                                        int mVideoWidth = Integer.parseInt(strings[0]);
                                        int mVideoHeight = Integer.parseInt(strings[1]);
                                        //解析出视频分辨率
                                        LogUtils.logout("handleMessage -->解析出视频分辨率: " + mVideoWidth + "," + mVideoHeight);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    break;
                                default:
                                    break;
                            }
                            return false;
                        }
                    }));
                    shop.getRepresentMonitorPlayer().startRealPlay();
                    shop.getRepresentMonitorPlayer().closeSound();
                }
            }else if (msg.what == MSG_TRY_AGAIN){
                startRealPlay();
            }
            return false;
        }
    });

    private void setView() {
        rlMask = findViewById(R.id.rl_mask);
        rlTalk = findViewById(R.id.rl_talk);
        imgCloseDialog = findViewById(R.id.img_close_dialog);
        tvTalkTip = findViewById(R.id.tv_talk_tip);
        miTalking = findViewById(R.id.mi_talking);

        rvShopList = findViewById(R.id.rv_shop_list);

    }

    private void initListView(){

        STORE_SPAN_COUNT = SharePreferencesUtils.readIntSharedPreferences(StoreListActivity.this, KEY_STORE_SPAN_COUNT);
        if (STORE_SPAN_COUNT == 0){
            STORE_SPAN_COUNT = 1;
        }
        rvShopList.setLayoutManager(new GridLayoutManager(this, STORE_SPAN_COUNT));
        adapter = new StoreAdapter(this, shopList);
        rvShopList.setAdapter(adapter);

        adapter.setOnItemClickListener(new StoreAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(StoreAdapter.LocalViewHolder holder, int position, Shop shop) {
                sSelectedShop = shop;
                startActivity(new Intent(StoreListActivity.this, CameraListActivity.class));
            }

            @Override
            public void onSoundSwitchClick(StoreAdapter.LocalViewHolder holder, int position, Shop shop) {
                if (shop.isRepresentMonitorSoundOn()){
                    shop.getRepresentMonitorPlayer().closeSound();
                    shop.setRepresentMonitorSoundOn(false);
                }else {
                    shop.getRepresentMonitorPlayer().openSound();
                    shop.setRepresentMonitorSoundOn(true);
                }
                adapter.notifyItemChanged(position, holder.imgSoundSwitch);
            }

            @Override
            public void onVoiceSwitchClick(StoreAdapter.LocalViewHolder holder, int position, Shop shop) {
                if (shop.isRepresentMonitorVoiceOn()){
                }else {
                    if (ContextCompat.checkSelfPermission(StoreListActivity.this,
                            Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(StoreListActivity.this,
                                new String[]{Manifest.permission.RECORD_AUDIO}, 0);
                        return;
                    }
                    shop.getRepresentMonitorPlayer().startVoiceTalk();
                    shop.setRepresentMonitorVoiceOn(true);
                    showTalkDialog();
                    currentTalkShop = shop;
                    currentTalkHolder = holder;
                    currentTalkPosition = position;
                }
                adapter.notifyItemChanged(position, holder.imgVoiceSwitch);
            }

            @Override
            public void onLockSwitchClick(final StoreAdapter.LocalViewHolder holder, final int position, final Shop shop) {
                watcherModel.setOutAllow(shop.getDevSn(), !shop.isOutAllow(), new NetCallback<ShopBell>() {
                    @Override
                    public void onSuccess(ShopBell myShop) {
                        shop.setOutAllow(myShop.isOutAllow());
                        adapter.notifyItemChanged(position, holder.imgLockSwitch);
                    }

                    @Override
                    public void onError(String msg) {
                        ToastUtils.showLongToast(StoreListActivity.this, "操作失败");
                    }
                });

            }
        });

        imgCloseDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideTalkDialog();

                currentTalkShop.getRepresentMonitorPlayer().stopVoiceTalk();
                currentTalkShop.setRepresentMonitorVoiceOn(false);
                adapter.notifyItemChanged(currentTalkPosition, currentTalkHolder.imgVoiceSwitch);
            }
        });
    }

    private void showTalkDialog() {
        rlMask.setVisibility(View.VISIBLE);
        rlTalk.setVisibility(View.VISIBLE);
        imgCloseDialog.setVisibility(View.VISIBLE);
        tvTalkTip.setVisibility(View.VISIBLE);
    }

    private void startTalkSuccess() {
        tvTalkTip.setVisibility(View.GONE);
        miTalking.setVisibility(View.VISIBLE);
    }

    private void startTalkFail() {
        tvTalkTip.setText("启动失败，点击重试");
    }

    private void hideTalkDialog() {
        rlMask.setVisibility(View.GONE);
        rlTalk.setVisibility(View.GONE);
        imgCloseDialog.setVisibility(View.GONE);
        tvTalkTip.setVisibility(View.GONE);
        miTalking.setVisibility(View.GONE);
    }

    private void getDeviceList() {
        watcherModel.getShopBellList(sShopWatcher.getShopWatcherId(), new NetCallback<List<ShopBell>>() {
            @Override
            public void onSuccess(final List<ShopBell> shops) {
                for (ShopBell shopBell:shops){
                    Shop shop = new Shop();
                    shop.setDevSn(shopBell.getDevSn());
                    shop.setAddr(shopBell.getAddr());
                    shop.setDevNum(shopBell.getDevNum());
                    shop.setOutAllow(shopBell.isOutAllow());
                    shop.setAlias(shopBell.getAlias());
                    shop.setLatitude(shopBell.getLatitude());
                    shop.setLongitude(shopBell.getLongitude());
                    shop.setOnline(shopBell.getOnline());
                    shop.setMonitors(new ArrayList<Monitor>());
                    for (MonitorBell monitorBell: shopBell.getMonitors()){
                        Monitor monitor = new Monitor();
                        monitor.setMonitorSn(monitorBell.getMonitorSn());
                        monitor.setMonitorName(monitorBell.getMonitorName());
                        shop.getMonitors().add(monitor);
                    }
                    shopList.add(shop);
                }

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            for (Shop shop: shopList){
                                if (shop.getMonitors() != null && shop.getMonitors().size() > 0) {
                                    Monitor representMonitor = shop.getMonitors().get(0);
                                    EZDeviceInfo deviceInfo = getOpenSDK().getDeviceInfo(representMonitor.getMonitorSn());
                                    if (deviceInfo.getCameraNum() > 0) {
                                        EZCameraInfo cameraInfo = EZUtils.getCameraInfoFromDevice(deviceInfo, 0);
                                        EZPlayer player = getOpenSDK()
                                                            .createPlayer(cameraInfo.getDeviceSerial(), cameraInfo.getCameraNo());
                                        shop.setMonitorOnline(deviceInfo.getStatus() == 1);
                                        shop.setRepresentMonitorPlayer(player);
                                        shop.setRepresentMonitorVerifyCode(representMonitor.getMonitorVerifyCode());
                                        shop.setRepresentMonitorSoundOn(false);
                                        shop.setRepresentMonitorVoiceOn(false);
                                    }
                                }
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    initListView();
                                    adapter.notifyDataSetChanged();
                                    isDataLoaded = true;
                                }
                            });
                        } catch (BaseException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Shop shop : shopList) {
            if (shop.getRepresentMonitorPlayer() != null){
                shop.getRepresentMonitorPlayer().release();
            }
        }
    }
}
